const router = require('koa-router')()
const fs = require('fs');
const path = require('path');
const mime = require('mime-types');
const exec = require('child_process').exec;
const ffmpeg = require('fluent-ffmpeg');
const spawn = require('child_process').spawn;
const db = require('../db/initdb');


function setMute(videoPath, outputPath) {
  return new Promise((resolve, reject) => {
    const ffmpeg = spawn('ffmpeg', [
      '-i', videoPath,
      '-c', 'copy',
      '-an',
      outputPath
    ]);

    ffmpeg.on('close', (code) => {
      console.log(` ffmpeg exit with code ${code}`);

      resolve();
    })
  })
}


function setMerge(audioPath, videoPath, outputPath) {
  return new Promise((resolve, reject) => {
    const ffmpeg = spawn('ffmpeg', [
      '-i', audioPath,
      '-i', videoPath,
      '-c:v', 'copy',
      '-c:a', 'aac',
      '-strict', 'experimental',
      outputPath
    ]);

    ffmpeg.on('close', (code) => {
      console.log(` ffmpeg exit with code ${code}`);

      resolve();
    })
  })
}

function addBgm(audioPath, videoPath, outputPath) {
  return new Promise((resolve, reject) => {
    const ffmpeg = spawn('ffmpeg', [
      '-i', audioPath,
      '-i', videoPath,
      '-filter_complex',
      'amix=inputs=2',
      outputPath
    ])

    // const ffmpeg = spawn('ffmpeg', [
    //   '-i', videoPath,
    //   '-i', audioPath,
    //   '-map', '0:v',
    //   '-map', '1:a',
    //   '-c:v', 'libx264',
    //   '-preset', 'veryfast',
    //   '-crf', '18',
    //   '-c:a', 'aac',
    //   '-b:a', '192k',
    //   outputPath,
    // ])

    ffmpeg.stdout.on('data', (data) => {
      console.log(`stdout: ${data}`);
    });

    ffmpeg.stderr.on('data', (data) => {
      console.error(`stderr: ${data} `);
    });

    ffmpeg.on('close', (code) => {
      console.log(` ffmpeg exit with code ${code}`);

      resolve();
    })
  })
}


router.prefix('/creator')

router.get('/', async (ctx, next) => {
  ctx.body = 'this is a creator response!'
})

router.get('/setMute', async (ctx, next) => {
  let sql = "select hs.card.image,hs.card.word from hs.card where hs.card.id=$1";
  let result = await db.query(sql, [ctx.query.id]);
  let videoPath = path.join(__dirname, `../public/images/${result.rows[0].image}`);

  let fileName = `${Date.now()}.mp4` // 重命名文件
  let outputPath = path.join(__dirname, '../public/images', fileName);
  let word = result.rows[0].word
  await setMute(videoPath, outputPath)
    .then(() => {
      ctx.body = {
        code: 200,
        message: 'success',
        fileName: fileName,
        word: word
      };
    })
})

router.get('/videoName', async (ctx, next) => {
  let sql = "select hs.card.image from hs.card where hs.card.id=$1";
  let result = await db.query(sql, [ctx.query.id]);
  console.log(result.rows[0].image)

  ctx.body = JSON.stringify(result.rows);
})

router.get('/getVideo', async (ctx, next) => {

  let videoPath = path.join(__dirname, `../public/images/${ctx.query.name}`);
  let videoContent = fs.readFileSync(videoPath);
  let mimeType = mime.lookup(videoPath);

  ctx.set('content-type', mimeType); //设置返回类型

  ctx.body = videoContent;


})

router.get('/bgm', async (ctx, next) => {
  let dirpath = path.join(__dirname, "../public/bgm");
  let dir = fs.readdirSync(dirpath);
  // let list = []
  // dir.forEach(item => {
  //   let filepath = path.join(__dirname, "../public/bgm/" + item);
  //   let file = fs.readFileSync(filepath);
  //   list.push(file);
  // })
  // console.log(dir);
  // console.log(list);

  ctx.body = dir;
})

router.get('/getbgm/:name', async (ctx, next) => {
  console.log(ctx.params.name);
  let filepath = path.join(__dirname, "../public/bgm/" + ctx.params.name)
  let file = fs.readFileSync(filepath)
  ctx.body = file
})

router.post('/recoding', async (ctx, next) => {
  const file = ctx.request.files.file // 获取上传的文件
  const reader = fs.createReadStream(file.filepath) // 创建可读流
  const ext = file.originalFilename.split('.')[2] // 获取文件后缀
  const fileName = `${Date.now()}.${ext}` // 重命名文件
  const filePath = path.join(__dirname, '../voice', fileName) // 文件保存路径

  const writer = fs.createWriteStream(filePath) // 创建可写流
  reader.pipe(writer) // 将可读流通过管道写入可写流

  ctx.body = '上传成功'
})

router.post('/merge', async (ctx, next) => {

  const file = ctx.request.files.file // 获取上传的文件
  const fileName = `${Date.now()}.mp4` // 重命名文件

  // 视频路径
  const videoPath = path.join(__dirname, `../public/images/${ctx.query.muteName}`);
  // 音频路径
  // const audioPath = path.join(__dirname, '../voice/岑宁儿-追光者.mp3');
  const audioPath = file.filepath;
  // 输出文件路径
  const outputPath = path.join(__dirname, '../public/images', fileName);


  await setMerge(audioPath, videoPath, outputPath)
    .then(() => {
      ctx.body = {
        code: 200,
        message: 'success',
        fileName: fileName
      };
    })
})

router.get('/addbgm', async (ctx, next) => {
  const fileName = `${Date.now()}.mp4` // 重命名文件
  console.log(fileName);
  // 视频路径
  const videoPath = path.join(__dirname, `../public/images/${ctx.query.name}`);
  // 音频路径
  const audioPath = path.join(__dirname, '../public/bgm/' + ctx.query.bgmName);
  // 输出文件路径
  const outputPath = path.join(__dirname, '../public/images', fileName);

  await addBgm(audioPath, videoPath, outputPath)
    .then(() => {
      ctx.body = {
        code: 200,
        message: 'success',
        fileName: fileName
      };
    })
})

router.post('/together', async (ctx, next) => {
  const file = ctx.request.files.file
  const fileName = `${Date.now()}.mp4` // 重命名文件
  console.log(fileName);
  // 视频路径
  const videoPath = path.join(__dirname, `../public/images/${ctx.query.name}`);
  // 音频路径
  // const audioPath = path.join(__dirname, '../public/images/11-景向谁依.mp3');
  const audioPath = file.filepath;
  console.log(audioPath);

  // 输出文件路径
  const outputPath = path.join(__dirname, '../public/images', fileName);

  await addBgm(audioPath, videoPath, outputPath)
    .then(() => {
      ctx.body = {
        code: 200,
        message: 'success',
        fileName: fileName
      };
    })
})

module.exports = router
